﻿using Arch.EntityFrameworkCore.UnitOfWork;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Common.dto;
using WebApi.context;

namespace WebApi.service
{
    public class BaseService<T>  : IBaseService<T> where T : BaseEntity
    {
        
        protected readonly IUnitOfWork<ToDoTaskContext> unitOfWork;

        public BaseService(IUnitOfWork<ToDoTaskContext> unitOfWork)
        {
            
            this.unitOfWork = unitOfWork;
        }

        public async Task<int> Add(T model)
        {
            IRepository<T> repository = unitOfWork.GetRepository<T>();

            await repository.InsertAsync(model);

            return await unitOfWork.SaveChangesAsync();
        }

        public  void Delete(int id)
        {
            IRepository<T> repository = unitOfWork.GetRepository<T>();
            repository.Delete(12);

            unitOfWork.SaveChanges();
        }

        public async Task<T> GetOrDefaultAsync(int id)
        {
            IRepository<T> repository = unitOfWork.GetRepository<T>();

            T entity = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id == id);
            
            return entity;
        }

        public void Update(T model)
        {
            IRepository<T> repository = unitOfWork.GetRepository<T>();
            repository.Update(model);

            unitOfWork.SaveChanges();
        }
    }
}
